package com.sgb.member.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityMemberApprovalBinding;
import com.sgb.member.entity.ApplyCompanyBean;
import com.sgb.member.entity.CompanyDeptBean;
import com.sgb.member.entity.MemberApprovalBean;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.event.EventConstant;
import com.sgb.member.event.MemberEvent;
import com.sgb.member.weight.MemberCommonDialog;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.customview.CfkEditView;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.DisplayUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

@Deprecated
// 会员审批信息填写
public class MemberApprovalActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private ActivityMemberApprovalBinding mBinding;
    private MemberApprovalModel sModel;
    private QualityMemberBean memberBean;
    private String approveType;
    // 会员审批信息Bean类
    private MemberApprovalBean approvalBean;
    private String companyId = "";

    private OptionsPickerView<CompanyDeptBean> mOptionDept;
    private OptionsPickerView<ApplyCompanyBean> mOptionCompany;

    public static void start(Context context, QualityMemberBean memberBean, String approveType) {
        start(context, memberBean, approveType, false);
    }

    /**
     * @param context
     * @param memberBean
     * @param approveType 审批类型 1 申请加盟(applyJoinCompany) 2邀请加盟(inviteJoinCompany)
     * @param isShopJump  是否从商品详情跳转过来
     */
    public static void start(Context context, QualityMemberBean memberBean, String approveType, boolean isShopJump) {
        Intent intent = new Intent(context, MemberApprovalActivity.class);
        intent.putExtra("Bean", memberBean);
        intent.putExtra("approveType", approveType);
        intent.putExtra("isShopJump", isShopJump);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void initView() {
        // 邀请加盟 inviteJoinCompany；申请加盟 applyJoinCompany
        approveType = getIntent().getStringExtra("approveType");
        memberBean = (QualityMemberBean) getIntent().getSerializableExtra("Bean");
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_member_approval);
        sModel = new ViewModelProvider(this).get(MemberApprovalModel.class);
        mBinding.setLifecycleOwner(this);
        mBinding.activityBar.titleView.setText("填写审批信息");
        mBinding.activityBar.ivBack.setOnClickListener(v -> finish());
        registerObserver();
    }

    @Override
    protected void init() {
        mBinding.itemApplyCompanyName.setMemberStyle();
        mBinding.itemApplyDepartment.setMemberStyle();
        mBinding.itemApplyName.setMemberStyle();
        mBinding.itemJoinCompanyName.setMemberStyle();
        mBinding.itemJoinCompanyType.setMemberStyle();
        mBinding.itemJoinAddress.setMemberStyle();
        setCfkEditViewStyle(mBinding.cftApplyDetail);
        setCfkEditViewStyle(mBinding.cftJoinBusiness);
        setCfkEditViewStyle(mBinding.cftCompanyProfile);
        mBinding.itemApplyCompanyName.setOnWholeItemClickListener(this);
        mBinding.itemApplyDepartment.setOnWholeItemClickListener(this);
        mBinding.itemJoinCompanyName.setOnWholeItemClickListener(this);
        mBinding.submit.setOnClickListener(this);

        mBinding.submit.setOnClickListener(this);
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if (TextUtils.isEmpty(companyNo) || "0".equals(companyNo)) {
            sModel.getUserInfo();
        } else {
            initUserInfo();
        }

    }

    private void initUserInfo() {
        String name = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String userNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        String companyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        mBinding.itemApplyCompanyName.setContent(companyName); //申请单位
        mBinding.itemApplyDepartment.setContent(""); // 申请部门
        mBinding.itemApplyName.setContent(name); // 申请人
        mBinding.itemJoinCompanyName.setContent(memberBean.getCompanyName()); // 企业名称
        mBinding.itemJoinCompanyType.setContent(memberBean.getServiceTypeName()); // 企业类型
        mBinding.itemJoinAddress.setContent(memberBean.getAddress()); //经营地址

        approvalBean = new MemberApprovalBean();
        approvalBean.setNo("");
        approvalBean.setApproveType(approveType);// 审批类型 1 申请加盟(固定传1就行) 2邀请加盟
        // 申请人信息
        approvalBean.setApplyUserName(name);
        approvalBean.setApplyUserNo(userNo);
        approvalBean.setApplyCompanyName(companyName);
        approvalBean.setApplyCompanyNo(companyNo);
        //加盟企业
        approvalBean.setJoinCompanyName(memberBean.getCompanyName());
        approvalBean.setJoinCompanyNo(memberBean.getCompanyNo());
        approvalBean.setJoinCompanyType(memberBean.getServiceTypeName());
        approvalBean.setJoinCompanyProvice(memberBean.getProvinceNo());
        approvalBean.setJoinCompanyCity(memberBean.getCityNo());
        approvalBean.setJoinCompanyArea(memberBean.getDistrictNo());
        approvalBean.setJoinCompanyBusinessAddress(memberBean.getAddress());
        boolean isShopJump = getIntent().getBooleanExtra("isShopJump", false);
        if (isShopJump) {
            // 跳转邀请加盟申请页 审批类型 1 申请加盟(固定传1就行) 2邀请加盟
            if ("2".equals(approveType)) { // 邀请加盟
                sModel.getProcessStatus(companyNo, "inviteJoinCompany");
            } else if ("1".equals(approveType)) { // 申请加盟
                sModel.getProcessStatus(companyNo, "applyJoinCompany");
            }
        } else {
            sModel.getMyCompanyList();
        }
    }

    private void setCfkEditViewStyle(CfkEditView editView) {
        editView.getEditText().setTextColor(getResources().getColor(R.color.FF000000));
        editView.getEditText().setHintTextColor(getResources().getColor(R.color.C0C4CC));
        editView.getEditText().setMinHeight(DisplayUtil.dip2px(this, 150));
    }

    private void registerObserver() {
        sModel.dialog.observe(this, aBoolean -> {
            if (aBoolean) {
                if (!DialogHelper.isShowing()) {
                    DialogHelper.showProgressDialog(MemberApprovalActivity.this, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
                }
            } else {
                DialogHelper.dismissProgressDialog();
            }
        });
        sModel.userInfo.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    initUserInfo();
                } else {
                    finish();
                }
            }
        });
        sModel.mCompanyList.observe(this, new Observer<List<ApplyCompanyBean>>() {
            @Override
            public void onChanged(List<ApplyCompanyBean> applyCompanyBeans) {
                if (TextUtils.isEmpty(companyId)) {
                    for (ApplyCompanyBean applyCompanyBean : applyCompanyBeans) {
                        if (applyCompanyBean.getComNo().equals(approvalBean.getApplyCompanyNo())) {
                            companyId = applyCompanyBean.getId();
                            return;
                        }
                    }
                }
                showCompanyPop(applyCompanyBeans);
            }
        });
        sModel.mDepList.observe(this, companyDeptBeans -> {
            if (companyDeptBeans != null && companyDeptBeans.size() > 0) {
                showDeptPop(companyDeptBeans);
            } else {
                MToast.showToast(MemberApprovalActivity.this, "申请部门暂时为空.");
            }
        });
        sModel.mApprovalStatus.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String status) {
                //1 表示有审批 0 代表无审批
                // 有审批时：弹出审批确认弹窗，具体如原型所示，点击去填写跳转到邀请审批信息填写页
                // 无审批时：点击去填写跳转到邀请信息填写页
                if ("1".equals(status)) {
                    MemberCommonDialog dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
                        @Override
                        public void onPositive(Object... objects) {
                            MemberCommonDialog dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
                                @Override
                                public void onPositive(Object... objects) {
                                    sModel.getMyCompanyList();
                                }
                            }, MemberCommonDialog.STYLE_INVITE_JOIN);
                            dialog.show(getActivity(), "MemberCommonDialog");
                        }
                    }, MemberCommonDialog.STYLE_CONFIRM_APPROVAL);
                    dialog.show(MemberApprovalActivity.this, "MemberCommonDialog");
                } else if ("0".equals(status)) {
                    // 跳转邀请加盟申请页 审批类型 1 申请加盟(固定传1就行) 2邀请加盟
                    if ("2".equals(approveType)) { // 邀请加盟
                        MemberInviteJoinActivity.start(MemberApprovalActivity.this, memberBean);
                    } else if ("1".equals(approveType)) { // 申请加盟
                        MemberApplyJoinActivity.start(MemberApprovalActivity.this, memberBean);
                    }
                    finish();
                } else {
                    MToast.showToast(MemberApprovalActivity.this, "网络链接不稳定，请稍后重试");
                    finish();
                }
            }
        });
        sModel.mApproveSuccess.observe(this, new Observer<BaseEntity>() {
            @Override
            public void onChanged(BaseEntity entity) {
                if ("0".equals(entity.getCode())) {
                    MToast.showToast(MemberApprovalActivity.this, "审批信息发送成功");
                    // 跳转至页面用户中心-审批列表-我发起的
                    MemberConfig.getInstance().getInstance().getInstance().startApprovalManager(MemberApprovalActivity.this, 1);
                    EventBus.getDefault().postSticky(MemberEvent.make()
                            .setMessageTag(EventConstant.EVENT_MEMBER_APPROVAL_SUCCESS)
                            .setMessageData(memberBean)
                    );
                    finish();
                } else {
                    MToast.showToast(MemberApprovalActivity.this, entity.getMsg());
                }
            }
        });
        sModel.mCompanyH5.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                MemberConfig.getInstance().getInstance().startWebViewX5(MemberApprovalActivity.this, s, 101);
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.item_join_company_name) {
            sModel.companyInfoDetail(memberBean.getCompanyId());
        } else if (id == R.id.item_apply_department) {
            if (sModel.mDepList.getValue() == null || sModel.mDepList.getValue().size() == 0) {
                if (TextUtils.isEmpty(companyId)) {
                    sModel.getMyCompanyList();
                } else {
                    sModel.getDeptList(companyId);
                }
                return;
            }
            showDeptPop(sModel.mDepList.getValue());
        } else if (id == R.id.item_apply_company_name) {
            if (sModel.mCompanyList.getValue() == null || sModel.mCompanyList.getValue().size() == 0) {
                sModel.getMyCompanyList();
                return;
            }
            showCompanyPop(sModel.mCompanyList.getValue());
        }
    }

    @Override
    public void onMultiClick(View v) {
        if (v.getId() == R.id.submit) {
            if (TextUtils.isEmpty(mBinding.cftApplyDetail.getEditContent())) {
                MToast.showToast(this, "请填写详情说明");
                return;
            }
            if (TextUtils.isEmpty(mBinding.cftJoinBusiness.getEditContent())) {
                MToast.showToast(this, "请列举1-5个该公司的主营业务");
                return;
            }
            String companyProfile = mBinding.cftCompanyProfile.getEditContent();
            if (!TextUtils.isEmpty(companyProfile)) {
                approvalBean.setJoinCompanyMainIntroduction(companyProfile);
            }
            approvalBean.setDetail(mBinding.cftApplyDetail.getEditContent());
            approvalBean.setJoinCompanyMainBusiness(mBinding.cftJoinBusiness.getEditContent());
           /* // 审批类型 1 申请加盟(固定传1就行) 2邀请加盟
            // 邀请加盟 inviteJoinCompany；申请加盟 applyJoinCompany
            switch (approveType) {
                case "1":
                    sModel.getProcessStatus(approvalBean.getApplyCompanyNo(), "inviteJoinCompany");
                    break;
                case "2":
                    sModel.getProcessStatus(approvalBean.getApplyCompanyNo(), "applyJoinCompany");
                    break;
            }*/
            MemberCommonDialog dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
                @Override
                public void onPositive(Object... objects) {
                    sModel.sendApprove(approvalBean);
                }
            }, MemberCommonDialog.STYLE_CONFIRM_APPROVAL);
            dialog.show(MemberApprovalActivity.this, "MemberCommonDialog");
        }
    }

    // 选择企业
    public void showCompanyPop(List<ApplyCompanyBean> mOptionData) {
        if (mOptionCompany == null) {
            mOptionCompany = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String name = mOptionData.get(options1).getName();
                String comNo = mOptionData.get(options1).getComNo();
                mBinding.itemApplyCompanyName.getContent_edt().setText(name);
                // 申请企业
                companyId = mOptionData.get(options1).getId();
                approvalBean.setApplyCompanyNo(comNo);
                approvalBean.setApplyCompanyName(name);
                sModel.mDepList.setValue(new ArrayList<>());
            }).setCancelColor(getResources().getColor(R.color.color_title_small)).build();
            mOptionCompany.setTitleText("选择企业");
        }
        mOptionCompany.setPicker(mOptionData);
        mOptionCompany.setSelectOptions(0);
        mOptionCompany.show();
    }

    // 选择部门
    public void showDeptPop(List<CompanyDeptBean> mOptionData) {
        if (mOptionDept == null) {
            mOptionDept = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String name = mOptionData.get(options1).getName();
                String id = mOptionData.get(options1).getId();
                mBinding.itemApplyDepartment.getContent_edt().setText(name);
                // 申请部门
                approvalBean.setApplyDeptNo(id);
                approvalBean.setApplyDeptName(name);
            }).setCancelColor(getResources().getColor(R.color.color_title_small)).build();
            mOptionDept.setTitleText("申请部门");
        }
        mOptionDept.setPicker(mOptionData);
        mOptionDept.setSelectOptions(0);
        mOptionDept.show();
    }
}
